package bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author mjy
 * @date 2021/12/07
 * @description
 */
public class BioDemo {

    public static void main(String[] args) throws Exception {

        //创建一个固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(128);

        ServerSocket serverSocket = new ServerSocket();
        //服务端绑定端口
        serverSocket.bind(new InetSocketAddress(1234));
        while (true) {
            Socket socket = serverSocket.accept();
            //为新的连接创建线程池执行任务
            executor.submit(new BioDemo().new ConnectionTask(socket));
        }
    }


    class ConnectionTask extends Thread {

        private Socket socket;


        public ConnectionTask(Socket socket) {
            this.socket = socket;
        }

        public Socket getSocket() {
            return socket;
        }

        public void setSocket(Socket socket) {
            this.socket = socket;
        }

        public void run() {
            while (true) {
                InputStream inputStream = null;
                OutputStream outputStream = null;
                try {
                    inputStream = socket.getInputStream();
                    outputStream = socket.getOutputStream();
                    outputStream.write(1);
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        inputStream.close();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }
        }
    }


}
